import React, { useState, useEffect } from 'react'
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { restrictToVerticalAxis } from '@dnd-kit/modifiers'
import {
  arrayMove,
  SortableContext,
  useSortable,
  verticalListSortingStrategy
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import './index.modules.scss'
import { baseURL } from '@/http/request'
import { PlusOutlined } from '@ant-design/icons'
import debounce from '@/components/js/throttle'
import {
  Space,
  Table,
  Button,
  Image,
  Modal,
  Card,
  message,
  Form,
  Upload,
  Input,
  Popconfirm,
  Pagination
} from 'antd'
import {
  carouselList,
  carouselAdd,
  carouselSort,
  carouselDelete
} from '@/http/api/resource'
let pageData = {
  page: 1,
  size: 10,
  total: 0
}

const Row = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key']
  })
  const style = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging
      ? {
          position: 'relative',
          zIndex: 9999
        }
      : {})
  }
  return (
    <tr
      {...props}
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
    />
  )
}
let _id = ''
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const handleChildMethod = () => {
    getList()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, serIsShowAdd] = useState(false)
  const [form] = Form.useForm()

  const columns = [
    {
      title: '内容',
      dataIndex: 'image',
      align: 'center',
      render: (image) => {
        return (
          <Image
            width={60}
            height={60}
            src={image}
            fallback=""
          />
        )
      }
    },
    {
      title: '内容名称',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              showModalAdd(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1
      }
    })
  )
  // 获取列表
  const getList = async () => {
    pageData.appid = localStorage.getItem('appid')
    const res = await carouselList({ pageData })
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  const onDragEnd = ({ active, over }) => {
    let dataList = []
    if (active.id !== over?.id) {
      setDataSource((prev) => {
        const activeIndex = prev.findIndex((i) => i.key === active.id)
        const overIndex = prev.findIndex((i) => i.key === over?.id)
        dataList = arrayMove(prev, activeIndex, overIndex)
        return arrayMove(prev, activeIndex, overIndex)
      })
    }
    debounce(() => {
      sortFn(dataList)
    }, 100)
  }

  const sortFn = async (data) => {
    await carouselSort(data)
  }
  const showModalAdd = (value) => {
    if (value._id) {
      let data = JSON.parse(JSON.stringify(value))
      form.setFieldsValue(data)
      _id = value._id
    }
    serIsShowAdd(true)
  }
  // 添加
  const onFinish = async (data) => {
    try {
      data.image = data.imageurl.fileList[0].response.image_url
      delete data.imageurl
      if (_id) {
        data._id = _id
      }
      data.appid = localStorage.getItem('appid')
      const res = await carouselAdd(data)
      form.resetFields()
      messageApi.success(res.data.res)
      serIsShowAdd(false)
      getList()
    } catch (error) {
      messageApi.error('失败')
    }
    _id = ''
  }
  const onFinishFailed = (data, a, b) => {
    console.log(data, a, b)
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await carouselDelete({ id: data._id })
    messageApi.success(res.data.messge)
    getList()
  }
  return (
    <div>
      <Card>
        <div className="headerButton">
          <Button
            type="primary"
            onClick={() => {
              serIsShowAdd(true)
            }}
          >
            添加内容
          </Button>
        </div>
        <DndContext
          sensors={sensors}
          modifiers={[restrictToVerticalAxis]}
          onDragEnd={onDragEnd}
        >
          <SortableContext
            items={dataSource.map((i) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              pagination={false}
              bordered
              components={{
                body: {
                  row: Row
                }
              }}
              rowKey="key"
              columns={columns}
              dataSource={dataSource}
            />
          </SortableContext>
        </DndContext>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      <div>
        <Modal
          title="添加"
          footer={[]}
          onCancel={() => {
            serIsShowAdd(false)
            form.resetFields()
          }}
          open={isShowAdd}
        >
          <Form
            labelCol={{
              span: 5
            }}
            wrapperCol={{
              span: 14
            }}
            layout="horizontal"
            style={{
              maxWidth: 800
            }}
            form={form}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <Form.Item
              label="图片名称"
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入名称'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="图片"
              name="imageurl"
              rules={[
                {
                  required: true,
                  message: '请选择图片'
                }
              ]}
            >
              <Upload
                maxCount={1}
                action={baseURL + 'api/uploadAvatar'}
                listType="picture-card"
              >
                <button
                  style={{
                    border: 0,
                    background: 'none'
                  }}
                  type="button"
                >
                  <PlusOutlined />
                  <div
                    style={{
                      marginTop: 8
                    }}
                  ></div>
                </button>
              </Upload>
            </Form.Item>
            <Form.Item
              label="图片备注"
              name="remark"
              rules={[
                {
                  required: true,
                  message: '请输入备注'
                }
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 6,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="primary"
                onClick={() => {
                  form.resetFields()
                  serIsShowAdd(false)
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {contextHolder}
    </div>
  )
})
export default App
